home *** CD-ROM | disk | FTP | other *** search
/ MacHack 1999 / MacHack 1999.toast / The Hacks / LiveFastStartServer / LiveFastStartServer.c < prev    next >
Encoding:
Text File  |  1999-06-26  |  33.0 KB  |  1,171 lines  |  [TEXT/CWIE]

  1. /*
  2.     File:        LiveFastStartServer.c by Sam Bushell
  3.         -- based on OTSimpleServerHTTP.c and HackTV.c
  4.  
  5.     Contains:    Implementation of the simple HTTP server sample.
  6.  
  7.     Written by:    Quinn "The Eskimo!"
  8.  
  9.     Copyright:    © 1997 by Apple Computer, Inc., all rights reserved.
  10.  
  11.     Change History (most recent first):
  12.     
  13.     08/27/97 - Rich Kubota - Included call to DoNegotiateIPReuseAddrOption
  14.                 so that on each endpoint, the IP level ReuseAddr option
  15.                 is enabled so that on immediate relaunch of the application,
  16.                 the designated IP addresses could be reused without IP
  17.                 protecting them until the timeout occurs.
  18.  
  19.     You may incorporate this sample code into your applications without
  20.     restriction, though the sample code has been provided "AS IS" and the
  21.     responsibility for its operation is 100% yours.  However, what you are
  22.     not permitted to do is to redistribute the source as "DSC Sample Code"
  23.     after having made changes. If you're going to re-distribute the source,
  24.     we require that you make it clear in the source that the code was
  25.     descended from Apple Sample Code, but that you've made changes.
  26.     
  27.     =====================================================================
  28.     
  29.     Let me make this clear: this source was descended (sic) from Apple Sample Code,
  30.     but I've made changes.  Horrible changes.  
  31.     
  32.     Sam Bushell
  33.     MacHack, June 1999
  34.     
  35. */
  36.  
  37. /////////////////////////////////////////////////////////////////////
  38. // The OT debugging macros in <OTDebug.h> require this variable to
  39. // be set.
  40.  
  41. #ifndef qDebug
  42. #define qDebug    1
  43. #endif
  44.  
  45. /////////////////////////////////////////////////////////////////////
  46. // Pick up all the standard OT stuff.
  47.  
  48. #include <OpenTransport.h>
  49.  
  50. /////////////////////////////////////////////////////////////////////
  51. // Pick up all the OT TCP/IP stuff.
  52.  
  53. #include <OpenTptInternet.h>
  54.  
  55. /////////////////////////////////////////////////////////////////////
  56. // Pick up the OTDebugBreak and OTAssert macros.
  57.  
  58. //#include <OTDebug.h>
  59. #define OTAssert(x,y) if(!(y)) printf(x);
  60.  
  61. /////////////////////////////////////////////////////////////////////
  62. // Pick up the various Thread Manager APIs.
  63.  
  64. #include <Threads.h>
  65.  
  66. /////////////////////////////////////////////////////////////////////
  67.  
  68. #include <stdio.h>
  69. #include <string.h>
  70.  
  71. #include <Endian.h>
  72. #include <Menus.h>
  73. #include <Script.h>
  74. #include <ImageCompression.h>
  75. #include <QuickTimeComponents.h>
  76. #include <Files.h>
  77. #include <Events.h>
  78. #include <MacWindows.h>
  79. #include <Resources.h>
  80. #include <NumberFormatting.h>
  81. #include <Strings.h>
  82.  
  83. /////////////////////////////////////////////////////////////////////
  84. // Pick up our own prototype.
  85.  
  86. #include "LiveFastStartServer.h"
  87.  
  88. /////////////////////////////////////////////////////////////////////
  89. // OTDebugStr is not defined in any OT header files, but it is
  90. // exported by the libraries, so we define the prototype here.
  91.  
  92. extern pascal void OTDebugStr(const char* str);
  93.  
  94. /////////////////////////////////////////////////////////////////////
  95. // When this boolean is to set true, this module assumes that the
  96. // host application is trying to quit and all the threads created by
  97. // this module start dying.  See the associated comment in the
  98. // YieldingNotifier routine.
  99.  
  100. extern Boolean gQuitNow = false;
  101.  
  102. // RRK Comments added 8/27/97
  103. // DoNegotiateIPReuseAddrOption is defined in the file
  104. // EnableIPReuseAddrSample.c.  This call uses the OTOptionManagement function
  105. // to set the IP level ResuseAddr option so that an IP address can be
  106. // reused on immediate relaunch of the application.
  107. extern OSStatus DoNegotiateIPReuseAddrOption(EndpointRef ep, Boolean enableReuseIPMode);
  108.  
  109. /////////////////////////////////////////////////////////////////////
  110.  
  111. static pascal void YieldingNotifier(EndpointRef ep, OTEventCode code, 
  112.                                        OTResult result, void* cookie)
  113.     // This simple notifier checks for kOTSyncIdleEvent and
  114.     // when it gets one calls the Thread Manager routine
  115.     // YieldToAnyThread.  Open Transport sends kOTSyncIdleEvent
  116.     // whenever it's waiting for something, eg data to arrive
  117.     // inside a sync/blocking OTRcv call.  In such cases, we
  118.     // yield the processor to some other thread that might
  119.     // be doing useful work.
  120.     //
  121.     // The routine also checks the gQuitNow boolean to see if the
  122.     // the host application wants us to quit.  This roundabout technique
  123.     // avoids a number of problems including:
  124.     //
  125.     // 1. Threads stuck inside OT synchronous calls -- You can't just
  126.     //    call DisposeThread on a thread that's waiting for an OT
  127.     //    synchronous call to complete.  Trust me, it would be bad!
  128.     //    Instead, this routine calls OTCancelSynchronousCalls to get
  129.     //    out of the call.  The given error code (userCanceledErr) 
  130.     //    propagates out to the caller, which causes the calling
  131.     //    thread to eventually terminate.
  132.     // 2. Threads holding resources -- You can't just DisposeThread
  133.     //    a networking thread because it might be holding resouces,
  134.     //    like memory or endpoints, that need to be cleaned up properly.
  135.     //    Cancelling the thread in this way causes the thread's own
  136.     //    code to clean up those resources just like it would for any
  137.     //    any other error.
  138.     //
  139.     // I could have used a more sophisticated mechanism to support
  140.     // quitting (such as a boolean per thread, or returning some
  141.     // "thread object" to which the application can send a "cancel"
  142.     // message, but this way is easy and works just fine for this
  143.     // simple sample
  144. {
  145.     #pragma unused(result)
  146.     #pragma unused(cookie)
  147.     OSStatus junk;
  148.     
  149. //DebugStr( "\p YieldingNotifier" );
  150.  
  151.     switch (code) {
  152.         case kOTSyncIdleEvent:
  153.             junk = YieldToAnyThread();
  154.             OTAssert("YieldingNotifier: YieldToAnyThread failed", junk == noErr);
  155.             
  156.             if (gQuitNow) {
  157.                 junk = OTCancelSynchronousCalls(ep, userCanceledErr);
  158.                 OTAssert("YieldingNotifier: Failed to cancel", junk == noErr);
  159.             }
  160.             break;
  161.         default:
  162.             // do nothing
  163.             break;
  164.     }
  165. }
  166.  
  167. /////////////////////////////////////////////////////////////////////
  168.  
  169. static void SetDefaultEndpointModes(EndpointRef ep)
  170.     // This routine sets the supplied endpoint into the default
  171.     // mode used in this application.  The specifics are:
  172.     // blocking, synchronous, and using synch idle events with
  173.     // the standard YieldingNotifier.
  174. {
  175.     OSStatus junk;
  176.     
  177. //DebugStr( "\p SetDefaultEndpointModes" );
  178.     junk = OTSetBlocking(ep);
  179.     OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
  180.     junk = OTSetSynchronous(ep);
  181.     OTAssert("SetDefaultEndpointModes: Could not set synchronous", junk == noErr);
  182.     junk = OTInstallNotifier(ep, &YieldingNotifier, ep);
  183.     OTAssert("SetDefaultEndpointModes: Could not install notifier", junk == noErr);
  184.     junk = OTUseSyncIdleEvents(ep, true);
  185.     OTAssert("SetDefaultEndpointModes: Could not use sync idle events", junk == noErr);
  186. }
  187.  
  188. /////////////////////////////////////////////////////////////////////
  189.  
  190. static OSStatus OTSndQ(EndpointRef ep, void *buf, size_t nbytes)
  191.     // My own personal wrapper around the OTSnd routine that cleans
  192.     // up the error result.
  193. {
  194.     OTResult bytesSent;
  195.     
  196. //DebugStr("\p OTSnd before" );
  197.     bytesSent = OTSnd(ep, buf, nbytes, 0);
  198. //DebugStr("\p OTSnd after" );
  199.     if (bytesSent >= 0) {
  200.     
  201.         // Because we're running in synchronous blocking mode, OTSnd
  202.         // should not return until it has sent all the bytes unless it
  203.         // gets an error.  If it does, we want to hear about it.
  204.         OTAssert("OTSndQ: Not enough bytes sent", bytesSent == nbytes);
  205.     
  206.         return (noErr);
  207.     } else {
  208.         return (bytesSent);
  209.     }
  210. }
  211.  
  212. /////////////////////////////////////////////////////////////////////
  213.  
  214. static OSErr FSReadQ(short refNum, long count, void *buffPtr)
  215.     // My own wrapper for FSRead.  Whose bright idea was it for
  216.     // it to return the count anyway!
  217. {
  218.     OSStatus err;
  219.     long tmpCount;
  220.     
  221.     tmpCount = count;
  222.     err = FSRead(refNum, &count, buffPtr);
  223.     
  224.     OTAssert("FSReadQ: Did not read enough bytes", (err != noErr) || (count == tmpCount));
  225.     
  226.     return (err);
  227. }
  228.  
  229. /////////////////////////////////////////////////////////////////////
  230.  
  231. static Boolean StringHasSuffix(const char *str, const char *suffix)
  232.     // Returns true if the end of str is suffix.
  233. {
  234.     Boolean result;
  235.     
  236.     result = false;
  237.     if ( OTStrLength(str) >= OTStrLength(suffix) ) {
  238.         if ( OTStrEqual(str + OTStrLength(str) - OTStrLength(suffix) , suffix) ) {
  239.             result = true;
  240.         }
  241.     }
  242.     
  243.     return (result);
  244. }
  245.  
  246. static OSStatus ExtractRequestedFileName(const char *buffer,
  247.                                             char *fileName, char *mimeType)
  248.     // Assuming that buffer is a C string contain an HTTP request,
  249.     // extract the name of the file that's being requested.
  250.     // Also check to see if the file has one of the common suffixes,
  251.     // and set mimeType appropriately.
  252.     //
  253.     // Obviously this routine should use Internet Config to
  254.     // map the file type/creator/extension to a MIME type,
  255.     // but I don't want to complicate the sample with that code.
  256. {
  257.     OSStatus err;
  258.     
  259.     // Default the result to empty.
  260.     fileName[0] = 0;
  261.     
  262.     // Scan the request looking for the fileName.  Obviously this is not
  263.     // a very good validation of the request, but this is an OT sample,
  264.     // not an HTTP one.  Also note that we require HTTP/1.0, but some
  265.     // ancient clients might just generate "GET %s<cr><lf>"
  266.     
  267.     (void) sscanf(buffer, "GET %s HTTP/1.0", fileName);
  268.     
  269.     // If the file name is still blank, scanf must have failed.
  270.     // Note that I don't rely on the result from scanf because in a
  271.     // previous life I learnt to mistrust it.
  272.     
  273.     if (fileName[0] == 0) {
  274.         err = -1;
  275.     } else {
  276.     
  277.         // So the request is cool.  Normalise the file name.
  278.         // Requests for the root return "index.html".
  279.         
  280.         if ( OTStrEqual(fileName, "/") ) {
  281.             OTStrCopy(fileName, "index.html");
  282.         }
  283.         
  284.         // Remove the prefix slash.  Note that we don't deal with
  285.         // "slashes" embedded in the fileName, so we don't handle
  286.         // any directories other than the root.  This would be
  287.         // easy to do, but again this is not an HTTP sample.
  288.         
  289.         if ( fileName[0] == '/' ) {
  290.             BlockMoveData(&fileName[1], &fileName[0], OTStrLength(fileName));
  291.         }
  292.     
  293.         // Set mimeType based on the file's suffix.
  294.         
  295.         if ( StringHasSuffix(fileName, ".html") ) {
  296.             OTStrCopy(mimeType, "text/html");
  297.         } else if ( StringHasSuffix(fileName, ".gif") ) {
  298.             OTStrCopy(mimeType, "image/gif");
  299.         } else if ( StringHasSuffix(fileName, ".jpg") ) {
  300.             OTStrCopy(mimeType, "image/jpeg");
  301.         } else if ( StringHasSuffix(fileName, ".mov") ) {
  302.             OTStrCopy(mimeType, "video/quicktime");
  303.         } else {
  304.             OTStrCopy(mimeType, "text/plain");
  305.         }
  306.         err = noErr;
  307.     }
  308.     
  309.     #if qDebug
  310.         printf("ExtractRequestedFileName: Returning %d, “%s”, “%s”\n", err, fileName, mimeType);
  311.     #endif
  312.     
  313.     return (err);
  314. }
  315.  
  316. /////////////////////////////////////////////////////////////////////
  317.  
  318. // The worker thread reads characters one at a time from the endpoint
  319. // and uses the following state machine to determine when the request is
  320. // finished.  For HTTP/1.0 requests, the request is terminated by
  321. // two consecutive CR LF pairs.  Each time we read one of the appropriate
  322. // characters we increment the state until we get to kDone, at which
  323. // point we go off to process the request.
  324.  
  325. enum {
  326.     kWorkerWaitingForCR1,
  327.     kWorkerWaitingForLF1,
  328.     kWorkerWaitingForCR2,
  329.     kWorkerWaitingForLF2,
  330.     kWorkerDone
  331. };
  332.  
  333. // This is the size of the transfer buffer that each worker thread
  334. // allocates to read file system data and write network data.
  335.  
  336. enum {
  337.     kTransferBufferSize = 4096
  338. };
  339.  
  340. // WorkerContext holds the information needed by a worker endpoint to
  341. // operate.  A WorkerContext is created by the listener endpoint
  342. // and passed as the thread parameter to the worker thread.  If the
  343. // listener successfully does this, it's assumed that the worker
  344. // thread has taken responsibility for freeing the context.
  345.  
  346. struct WorkerContext {
  347.     EndpointRef worker;
  348.     short vRefNum;
  349.     long dirID;
  350. };
  351. typedef struct WorkerContext WorkerContext, *WorkerContextPtr;
  352.  
  353. // The two buffers hold standard HTTP responses.  The first is the 
  354. // default text we spit out when we get an error.  The second is
  355. // the header that we use when we successfully field a request.
  356. // Again note that this sample is not about HTTP, so these responses
  357. // are probably not particularly compliant to the HTTP protocol.
  358.  
  359. char gDefaultOutputText[] = "HTTP/1.0 200 OK\15\12Content-Type: text/html\15\12\15\12<H1>Say what!</H1><P>\15\12Error Number (%d), Error Text (%s)";
  360. //char gHTTPHeader[] = "HTTP/1.0 200 OK\15\12Content-Type: %s\15\12\15\12";
  361. char gHTTPHeader[] = "HTTP/1.0 200 OK\15\12Pragma: no-cache\15\12Cache-Control: no-cache\15\12Content-Type: %s\15\12\15\12";
  362.  
  363. /////////////////////////////////////////////////////////////////////
  364.  
  365. static OSStatus ReadHTTPRequest(EndpointRef worker, char *buffer)
  366.     // This routine reads the HTTP request from the worker endpoint,
  367.     // using the state machine described above, and puts it into the
  368.     // indicated buffer.  The buffer must be at least kTransferBufferSize
  369.     // bytes big.
  370.     //
  371.     // This is pretty feeble
  372.     // code (reading data one byte at a time is bad for performance),
  373.     // but it works and I'm not quite sure how to fix it.  Perhaps
  374.     // OTCountDataBytes?
  375.     //
  376.     // Also, the code does not support with requests bigger than
  377.     // kTransferBufferSize.  In practise, this isn't a problem.
  378. {
  379.     OSStatus err;
  380.     long bufferIndex;
  381.     int state;
  382.     char ch;
  383.     OTResult bytesReceived;
  384.     OTFlags junkFlags;
  385.     
  386.     OTAssert("ReadHTTPRequest: What endpoint?", worker != nil);
  387.     OTAssert("ReadHTTPRequest: What buffer?", buffer != nil);
  388.     
  389.     bufferIndex = 0;
  390.     state = kWorkerWaitingForCR1;
  391.     do {    
  392.         bytesReceived = OTRcv(worker, &ch, sizeof(char), &junkFlags);
  393.         if (bytesReceived >= 0) {
  394.             OTAssert("ReadHTTPRequest: Didn't read the expected number of bytes", bytesReceived == sizeof(char));
  395.             
  396.             err = noErr;
  397.  
  398.             // Put the character into the buffer.
  399.             
  400.             buffer[bufferIndex] = ch;
  401.             bufferIndex += 1;
  402.             
  403.             // Check that we still have space to include our null terminator.
  404.             
  405.             if (bufferIndex >= kTransferBufferSize) {
  406.                 err = -1;
  407.             }
  408.             
  409.             // Do the magic state machine.  Note the use of
  410.             // hardwired numbers for CR and LF.  This is correct
  411.             // because the Internet standards say that these
  412.             // numbers can't change.  I don't use \n and \r
  413.             // because these values change between various C
  414.             // compilers on the Mac.
  415.             
  416.             switch (ch) {
  417.                 case 13:
  418.                     switch (state) {
  419.                         case kWorkerWaitingForCR1:
  420.                             state = kWorkerWaitingForLF1;
  421.                             break;
  422.                         case kWorkerWaitingForCR2:
  423.                             state = kWorkerWaitingForLF2;
  424.                             break;
  425.                         default:
  426.                             state = kWorkerWaitingForCR1;
  427.                             break;
  428.                     }
  429.                     break;
  430.                 case 10:
  431.                     switch (state) {
  432.                         case kWorkerWaitingForLF1:
  433.                             state = kWorkerWaitingForCR2;
  434.                             break;
  435.                         case kWorkerWaitingForLF2:
  436.                             state = kWorkerDone;
  437.                             break;
  438.                         default:
  439.                             state = kWorkerWaitingForCR1;
  440.                             break;
  441.                     }
  442.                     break;
  443.                 default:
  444.                     state = kWorkerWaitingForCR1;
  445.                     break;
  446.             }
  447.         } else {
  448.             err = bytesReceived;
  449.         }
  450.     } while ( err == noErr && state != kWorkerDone );
  451.  
  452.     if (err == noErr) {
  453.         // Append the null terminator that turns the HTTP request into a C string.
  454.         buffer[bufferIndex] = 0;
  455.     }
  456.  
  457.     return (err);        
  458. }
  459.  
  460. /////////////////////////////////////////////////////////////////////
  461.  
  462. static OSStatus CopyFileToEndpoint(const FSSpec *fileSpec, char *buffer, EndpointRef worker)
  463.     // Copy the file denoted by fileSpec to the endpoint.  buffer is a
  464.     // temporary buffer of size kTransferBufferSize.  Initially buffer
  465.     // contains a C string that is the HTTP header to output.  After that,
  466.     // the routine uses buffer as temporary storage.  We do this because
  467.     // we want any errors opening the file to be noticed before we send
  468.     // the header saying that the request went through successfully.
  469. {
  470.     OSStatus err;
  471.     OSStatus junk;
  472.     long bytesToSend;
  473.     long bytesThisTime;
  474.     short fileRefNum;
  475.     
  476.     err = FSpOpenDF(fileSpec, fsRdPerm, &fileRefNum);
  477.     if (err == noErr) {
  478.         err = GetEOF(fileRefNum, &bytesToSend);
  479.         
  480.         // Write the HTTP header out to the endpoint.
  481.         
  482.         if (err == noErr) {
  483.             err = OTSndQ(worker, buffer, OTStrLength(buffer));
  484.         }
  485.         
  486.         // Copy the file in kTransferBufferSize chunks to the endpoint.
  487.         
  488.         while (err == noErr && bytesToSend > 0) {
  489.             if (bytesToSend > kTransferBufferSize) {
  490.                 bytesThisTime = kTransferBufferSize;
  491.             } else {
  492.                 bytesThisTime = bytesToSend;
  493.             }
  494.             err = FSReadQ(fileRefNum, bytesThisTime, buffer);
  495.             if (err == noErr) {
  496.                 err = OTSndQ(worker, buffer, bytesThisTime);
  497.             }
  498.             bytesToSend -= bytesThisTime;
  499.         }
  500.         
  501.         // Clean up.
  502.         junk = FSClose(fileRefNum);
  503.         OTAssert("WorkerThreadProc: Could not close file", junk == noErr);
  504.     }
  505.     
  506.     return (err);
  507. }
  508.  
  509. /////////////////////////////////////////////////////////////////////
  510.  
  511. Handle gMovieHeader = nil;
  512. Handle gDummyFrame = nil;
  513. Handle gZero5000 = nil;
  514. //#define FRAMESIZE 5000
  515. #define FRAMESIZE 10000
  516.  
  517. OSErr InitLiveMovie()
  518. {
  519.     OSErr err;
  520.     
  521.     gMovieHeader = Get1Resource( 'moo ', 128 );
  522.     if( !gMovieHeader ) {
  523.         err = ResError();
  524.         DebugStr( "\p couldn't get the movie header resource" );
  525.         goto bail;
  526.     }
  527.     HLockHi( gMovieHeader );
  528.     
  529.     gZero5000 = NewHandleClear( FRAMESIZE );
  530.     err = MemError();
  531.     if( err ) {
  532.         DebugStr( "\p couldn't allocate some zeros." );
  533.         goto bail;
  534.     }
  535.     HLockHi( gZero5000 );
  536.     
  537.     gDummyFrame = Get1Resource( '   v', 128 );
  538.     if( !gDummyFrame ) {
  539.         err = ResError();
  540.         DebugStr( "\p couldn't get the dummy frame" );
  541.         goto bail;
  542.     }
  543.     DetachResource( gDummyFrame );
  544.     SetHandleSize( gDummyFrame, FRAMESIZE );
  545.     HLockHi( gDummyFrame );
  546.     if( GetHandleSize( gDummyFrame ) != FRAMESIZE ) 
  547.         DebugStr( "\p warning: dummy frame isn't 5000 bytes" );
  548.     
  549. bail:
  550.     return err;
  551. }
  552.  
  553. /* ---------------------------------------------------------------------- */
  554.  
  555. static pascal Boolean
  556. SeqGrabberModalFilterProc (DialogPtr theDialog, EventRecord *theEvent,
  557.     short *itemHit, long refCon)
  558. {
  559.     // Ordinarily, if we had multiple windows we cared about, we'd handle
  560.     // updating them in here, but since we don't, we'll just clear out
  561.     // any update events meant for us
  562.     
  563.     Boolean    handled = false;
  564.     
  565.     if ((theEvent->what == updateEvt) && 
  566.         ((WindowPtr) theEvent->message == (WindowPtr) refCon))
  567.     {
  568.         WindowPtr    wPtr = (WindowPtr) refCon;
  569.         BeginUpdate (wPtr);
  570.         EndUpdate (wPtr);
  571.         handled = true;
  572.     }
  573.     return (handled);
  574. }
  575.  
  576. /* ---------------------------------------------------------------------- */
  577.  
  578. pascal ComponentResult myAddFrameProc( SGChannel c, short bufferNum, TimeValue atTime, TimeScale scale, const SGCompressInfo *ci, long refCon );
  579.  
  580. SeqGrabComponent        gSeqGrabber = 0;
  581. SGChannel                gVideoChannel = 0;
  582. WindowPtr                gMonitor = 0;
  583. ICMAlignmentProcRecord    gSeqGrabberAlignProc = {0,0};
  584. SGAddFrameBottleUPP        gAddFrameProc = 0;
  585.  
  586. OSErr InitGrabber()
  587. {
  588.     OSErr err;
  589.     SGModalFilterUPP    seqGragModalFilterUPP = 0;
  590.     VideoBottles vb;
  591.     ComponentDescription cd;
  592.     CompressorComponent cJPEG = 0;
  593.     
  594.     EnterMovies();
  595.     
  596.     err = OpenADefaultComponent( SeqGrabComponentType, 0, &gSeqGrabber );
  597.     if( err ) { DebugStr( "\p open barg" ); goto bail; }
  598.     
  599.     
  600.     gMonitor = GetNewDialog (129, nil, (WindowPtr)-1L);
  601.     SetPort( gMonitor );
  602.     SizeWindow( gMonitor, 320, 240, false );
  603.     ShowWindow( gMonitor );
  604.     
  605.     err = SGInitialize( gSeqGrabber );
  606.     if( err ) { DebugStr( "\p init barg" ); goto bail; }
  607.     
  608.     err = SGSetGWorld (gSeqGrabber, (CGrafPtr) gMonitor, nil);
  609.     if( err ) { DebugStr( "\p sgsetgworld" ); goto bail; }
  610.  
  611.     err = SGNewChannel (gSeqGrabber, VideoMediaType, &gVideoChannel);
  612.     if( err ) { DebugStr( "\p new video channel" ); goto bail; }
  613.  
  614.     err = SGSetChannelUsage (gVideoChannel, seqGrabRecord);
  615.     if( err ) { DebugStr( "\p set channel usage" ); goto bail; }
  616.  
  617.     err = SGSetChannelBounds (gVideoChannel, &(gMonitor->portRect));
  618.     if( err ) { DebugStr( "\p set channel bounds" ); goto bail; }
  619.  
  620.     err = SGGetAlignmentProc (gSeqGrabber, &gSeqGrabberAlignProc);
  621.     if( err ) { DebugStr( "\p get align rect proc" ); goto bail; }
  622.  
  623. #if 0
  624.     err = SGSetVideoCompressorType(gVideoChannel, kJPEGCodecType );
  625.     if( err ) { DebugStr( "\p SGSetVideoCompressorType" ); goto bail; }
  626. #else
  627.     cd.componentType = compressorComponentType;
  628.     cd.componentSubType = kJPEGCodecType;
  629.     cd.componentManufacturer = 0;
  630.     cd.componentFlags = 0;
  631.     cd.componentFlagsMask = 0;
  632.     cJPEG = FindNextComponent( 0, &cd );
  633.     if( !cJPEG ) DebugStr( "\p can't find JPEG compressor!" );
  634.     
  635.     err = SGSetVideoCompressor(gVideoChannel, 24, cJPEG, codecMinQuality, 0, 0 );
  636.     if( err ) { DebugStr( "\p SGSetVideoCompressor" ); goto bail; }
  637. #endif
  638.  
  639.     err = SGSetFrameRate( gVideoChannel, 4L<<16 ); // FPS is 4
  640.     if( err ) { DebugStr( "\p SGSetFrameRate" ); goto bail; }
  641.  
  642.     gAddFrameProc = NewSGAddFrameBottleProc( myAddFrameProc );
  643.  
  644.     /* get the current bottlenecks */
  645.     vb.procCount = 9;
  646.     err = SGGetVideoBottlenecks (gVideoChannel, &vb);
  647. //    vb.grabCompleteProc = myGrabFrameComplete;
  648.     vb.addFrameProc = gAddFrameProc;
  649.     err = SGSetVideoBottlenecks (gVideoChannel, &vb); 
  650.  
  651.     seqGragModalFilterUPP = (SGModalFilterUPP)NewSGModalFilterProc(SeqGrabberModalFilterProc);
  652.     err = SGSettingsDialog(gSeqGrabber, gVideoChannel, 0, 
  653.         nil, 0L, seqGragModalFilterUPP, (long)StripAddress ((Ptr) gMonitor));
  654.     DisposeRoutineDescriptor(seqGragModalFilterUPP);
  655.     if( err ) { DebugStr( "\p settings dialog" ); goto bail; }
  656.  
  657.     err = SGStartPreview (gSeqGrabber);
  658.     if( err ) { DebugStr( "\p start preview" ); goto bail; }
  659.  
  660. bail:
  661.     return err;
  662. }
  663.  
  664. OSErr IdleGrabber()
  665. {
  666.     if (gSeqGrabber)
  667.         SGIdle (gSeqGrabber);
  668.     return noErr;
  669. }
  670.  
  671. Boolean IsGrabberEvent( EventRecord *event )
  672. {
  673.     switch (event->what) {
  674.         case updateEvt:
  675.             if ((gMonitor != nil) && ((WindowPtr) (event->message) == (WindowPtr) gMonitor))
  676.             {
  677.                 SGUpdate(gSeqGrabber, ((WindowPeek)gMonitor)->updateRgn);
  678.                 BeginUpdate (gMonitor);
  679.                 EndUpdate (gMonitor);
  680.                 return true;
  681.             }
  682.             break;
  683.         case mouseDown:
  684.         {
  685.             WindowPtr    theWindow;
  686.             short        windowCode = MacFindWindow (event->where, &theWindow);
  687.             
  688.             if ( (windowCode == inDrag) && (theWindow == gMonitor) )
  689.             {
  690.                 ComponentResult    result = noErr;
  691.                 Rect            limitRect;
  692.                 RgnHandle        grayRgn = GetGrayRgn();
  693.                 Rect            boundsRect;
  694.                 
  695.                 // Find bounds
  696.                 if (grayRgn != nil)
  697.                 {
  698.                     limitRect = (*grayRgn)->rgnBBox;
  699.                 }
  700.                 else
  701.                 {
  702.                     limitRect = qd.screenBits.bounds;
  703.                 }
  704.                 
  705.                 // Pause the sequence grabber
  706.                 result = SGPause (gSeqGrabber, true);
  707.                 
  708.                 if (gVideoChannel != nil)
  709.                 {
  710.                     // Drag it with the totally cool DragAlignedWindow
  711.                       result = SGGetChannelBounds (gVideoChannel, &boundsRect);
  712.                     DragAlignedWindow (theWindow, event->where, &limitRect, &boundsRect, &gSeqGrabberAlignProc);
  713.                 }
  714.                 else
  715.                 {
  716.                     DragWindow (theWindow, event->where, &limitRect);
  717.                 }
  718.                 
  719.                 // Start up the sequence grabber
  720.                 result = SGPause (gSeqGrabber, false);
  721.                 
  722.                 return true;
  723.             }
  724.         }
  725.             break;
  726.     }
  727.     return false;
  728. }
  729.  
  730. OSErr KillGrabber()
  731. {
  732.     CloseComponent( gSeqGrabber );
  733.     gSeqGrabber = 0;
  734.     
  735.     if( gMonitor )
  736.         DisposeDialog( gMonitor );
  737.     gMonitor = 0;
  738.     
  739.     return noErr;
  740. }
  741.  
  742. EndpointRef gGrabberEndpoint = 0;
  743. long gFrameCount = 0;
  744. OSErr gGrabberErr = noErr;
  745.  
  746. static OSErr StartGrabbing( EndpointRef worker )
  747. {
  748.     OSErr err;
  749.     
  750.     if( gGrabberEndpoint ) {
  751.         DebugStr( "\p already in use!" );
  752.         return paramErr; // (lame)
  753.     }
  754.     gGrabberEndpoint = worker;
  755.     gGrabberErr = noErr;
  756.     
  757.     err = SGSetDataOutput( gSeqGrabber, nil, seqGrabDontMakeMovie );
  758.     if (err) {
  759.         DebugStr( "\p SGSetDataOutput failed." );
  760.         goto bail;
  761.     }
  762.     
  763.     err = SGStartRecord(gSeqGrabber);
  764.     if (err) {
  765.         DebugStr( "\p SGStartRecord failed." );
  766.         goto bail;
  767.     }
  768.  
  769. bail:
  770.     return err;
  771. }
  772.  
  773. #define TRACK_BIGGEST_FRAME 1
  774. #if TRACK_BIGGEST_FRAME
  775. long gBiggestFrame = 0;
  776. #endif // TRACK_BIGGEST_FRAME
  777.  
  778. pascal ComponentResult myAddFrameProc( SGChannel c, short bufferNum, 
  779.             TimeValue atTime, TimeScale scale, const SGCompressInfo *ci, long refCon )
  780. {
  781.     OSErr err;
  782.     
  783.     if( !gGrabberEndpoint || gGrabberErr )
  784.         return noErr;
  785.     
  786.     if( ci->bufferSize > FRAMESIZE ) {
  787. #if TRACK_BIGGEST_FRAME
  788.         if( gBiggestFrame < ci->bufferSize ) {
  789.             Str255 str;
  790.             gBiggestFrame = ci->bufferSize;
  791.             
  792.             NumToString( gBiggestFrame, str );
  793.             str[++str[0]] = ';';
  794.             str[++str[0]] = 'g';
  795.             DebugStr( str );
  796.         }
  797. #endif // TRACK_BIGGEST_FRAME
  798.  
  799.         // too big.  fall back to dummy frame.
  800.         err = OTSndQ( gGrabberEndpoint, *gDummyFrame, GetHandleSize( gDummyFrame ) );
  801.     }
  802.     else {
  803.         // small enough.  send it along.
  804.         err = OTSndQ( gGrabberEndpoint, ci->buffer, ci->bufferSize );
  805.         if( err ) goto bail;
  806.         err = OTSndQ( gGrabberEndpoint, *gZero5000, FRAMESIZE - ci->bufferSize );
  807.     }
  808.     
  809. bail:
  810.     if( err )
  811.         gGrabberErr = err;
  812.     return err;
  813. }
  814.  
  815. static OSErr StopGrabbing( EndpointRef worker )
  816. {
  817.     OSErr err;
  818.     
  819.     if( gGrabberEndpoint == worker ) {
  820.         gGrabberEndpoint = 0;
  821.         
  822.         //••
  823.         err = SGStop(gSeqGrabber);
  824.         err = SGStartPreview(gSeqGrabber);
  825.     }
  826.     return noErr;
  827. }
  828.  
  829. static OSStatus CopyLiveMovieToEndpoint(char *buffer, EndpointRef worker)
  830. {
  831.     OSStatus err;
  832. //    long i;
  833.     
  834.     // Write the HTTP header out to the endpoint.
  835.     
  836.     err = OTSndQ( worker, buffer, OTStrLength(buffer) );
  837.     if( err ) goto bail;
  838.     
  839.     // Write the movie header.
  840.     err = OTSndQ( worker, *gMovieHeader, GetHandleSize(gMovieHeader) );
  841.     if( err ) goto bail;
  842.     
  843.     YieldToAnyThread();
  844.  
  845.     err = StartGrabbing( worker );
  846.     if( err ) goto bail;
  847.     
  848.     // Write movie frames.
  849.     gFrameCount = 0;
  850.     while( (gFrameCount < 1500) && gGrabberEndpoint && !gGrabberErr ) {
  851.         YieldToAnyThread();
  852.     }
  853.     /*
  854.     for( i = 0; i < 1500; i++ ) {
  855.         Size size = GetHandleSize( gDummyFrame );
  856.         //••
  857.         
  858.         if( size != FRAMESIZE )
  859.             DebugStr( "\p warning: dummy frame isn't 5000 bytes" );
  860.         
  861.         err = OTSndQ( worker, *gDummyFrame, size );
  862.         if( err ) goto bail;
  863.         
  864.         YieldToAnyThread();
  865.     }
  866.     */
  867.     
  868. bail:
  869.     StopGrabbing( worker );
  870.  
  871.     return err;
  872. }
  873.  
  874. // demo movie with just dummy frames.
  875. static OSStatus CopyOliveMovieToEndpoint(char *buffer, EndpointRef worker)
  876. {
  877.     OSStatus err;
  878.     long i;
  879.     
  880.     // Write the HTTP header out to the endpoint.
  881.     
  882.     err = OTSndQ( worker, buffer, OTStrLength(buffer) );
  883.     if( err ) goto bail;
  884.     
  885.     // Write the movie header.
  886.     err = OTSndQ( worker, *gMovieHeader, GetHandleSize(gMovieHeader) );
  887.     if( err ) goto bail;
  888.     
  889.     YieldToAnyThread();
  890.  
  891.     // Write movie frames.
  892.     for( i = 0; i < 1500; i++ ) {
  893.         Size size = GetHandleSize( gDummyFrame );
  894.         
  895.         if( size != FRAMESIZE )
  896.             DebugStr( "\p warning: dummy frame isn't 5000 bytes" );
  897.         
  898.         err = OTSndQ( worker, *gDummyFrame, size );
  899.         if( err ) goto bail;
  900.         
  901.         YieldToAnyThread();
  902.     }
  903.     
  904. bail:
  905.     return err;
  906. }
  907.  
  908. /////////////////////////////////////////////////////////////////////
  909.  
  910. static pascal OSStatus WorkerThreadProc(WorkerContextPtr context)
  911.     // This routine is the starting routine for the worker thread.
  912.     // The thread is responsible for reading an HTTP request from
  913.     // an endpoint, processing the requesting and writing the results
  914.     // back to the endpoint.
  915. {
  916.     OSStatus err;
  917.     OSStatus junk;
  918.     char *buffer = nil;
  919.     char *errStr;
  920.     char fileName[256];
  921.     char mimeType[256];
  922.     FSSpec fileSpec;
  923.     
  924.     printf("WorkerThreadProc: Starting\n");
  925.     fflush(stdout);
  926.     OTAssert("WorkerThreadProc: Context is nil!", context != nil);
  927.     OTAssert("WorkerThreadProc: Worker endpoint is nil!", context->worker != nil);
  928.  
  929.     // Allocate the transfer buffer in the heap.
  930.     
  931.     err = noErr;
  932.     buffer = OTAllocMem(kTransferBufferSize);
  933.     if (buffer == nil) {
  934.         err = kENOMEMErr;
  935.     }
  936.  
  937.     // Read the request into the transfer buffer.
  938.     
  939.     if (err == noErr) {
  940.         err = ReadHTTPRequest(context->worker, buffer);
  941.     }
  942.     
  943.     if (err == noErr) {
  944.  
  945.         // Get the requested file name (and it's mimeType) from the
  946.         // HTTP request in the transfer buffer.
  947.         
  948.         err = ExtractRequestedFileName(buffer, fileName, mimeType);
  949.         
  950.         if (err == noErr) {
  951.         
  952.             // Create the appropriate HTTP response in the buffer.
  953.             
  954.             sprintf(buffer, gHTTPHeader, mimeType);
  955.  
  956.             // Copy the file (with preceding HTTP header) to the endpoint.
  957.  
  958.             if( 0 == strcmp( fileName, "live.mov" ) ) {
  959.                 err = CopyLiveMovieToEndpoint( buffer, context->worker );
  960.             }
  961.             else if( 0 == strcmp( fileName, "olive.mov" ) ) {
  962.                 err = CopyOliveMovieToEndpoint( buffer, context->worker );
  963.             }
  964.             else {
  965.                 (void) FSMakeFSSpec(context->vRefNum, context->dirID, C2PStr(fileName), &fileSpec);
  966.                 err = CopyFileToEndpoint(&fileSpec, buffer, context->worker);
  967.             }
  968.         }
  969.         
  970.         // Handle any errors by sending back an appropriate error header.
  971.         
  972.         if (err != noErr) {
  973.             switch (err) {
  974.                 case fnfErr:
  975.                     errStr = "File Not Found";
  976.                     break;
  977.                 default:
  978.                     errStr = "Unknown Error";
  979.                     break;
  980.             }
  981.             sprintf(buffer, gDefaultOutputText, err, errStr);
  982.             err = OTSndQ(context->worker, buffer, OTStrLength(buffer));
  983.         }
  984.     }
  985.     
  986.     // Shut down the endpoint and clean up the WorkerContext.
  987.     
  988.     if (err == noErr) {
  989.         err = OTSndOrderlyDisconnect(context->worker);
  990.         if (err == noErr) {
  991.             err = OTRcvOrderlyDisconnect(context->worker);
  992.         }
  993.     }
  994.  
  995.     junk = OTCloseProvider(context->worker);
  996.     OTAssert("StartHTTPServer: Could not close listener", junk == noErr);
  997.     
  998.     OTFreeMem(context);
  999.  
  1000.     if (buffer != nil) {
  1001.         OTFreeMem(buffer);
  1002.     }
  1003.  
  1004.     printf("WorkerThreadProc: Stopping with final result %d.\n", err);
  1005.     fflush(stdout);
  1006.     
  1007.     return (noErr);
  1008. }
  1009.  
  1010. /////////////////////////////////////////////////////////////////////
  1011.  
  1012. OSStatus RunHTTPServer(InetHost ipAddr, short vRefNum, long dirID)
  1013.     // This routine runs an HTTP server.  It doesn't return until
  1014.     // someone sets gQuitNow, so you should most probably call this
  1015.     // routine on its own thread.  ipAddr is the IP address that
  1016.     // the server listens on.  Specify kOTAnyInetAddress to listen
  1017.     // on all IP addresses on the machine; specify an IP address
  1018.     // to listen on a specific address.  vRefNum and dirID point
  1019.     // to the root directory of the HTTP information to be served.
  1020.     //
  1021.     // The routine creates a listening endpoint and listens for connection 
  1022.     // requests on that endpoint.  When a connection request arrives, it creates 
  1023.     // a new worker thread (with accompanying endpoint) and accepts the connection
  1024.     // on that thread.
  1025.     //
  1026.     // Note the use of the "tilisten" module which prevents multiple
  1027.     // simultaneous T_LISTEN events coming from the transport provider,
  1028.     // thereby greatly simplifying the listen/accept sequence.
  1029. {
  1030.     OSStatus err;
  1031.     EndpointRef listener;
  1032.     TBind bindReq;
  1033.     InetAddress ipAddress;
  1034.     InetAddress remoteIPAddress;
  1035.     TCall call;
  1036.     ThreadID workerThread;
  1037.     OSStatus junk;
  1038.     WorkerContextPtr workerContext;
  1039.     TEndpointInfo Info;
  1040.     char    buf[128];
  1041.     
  1042.     // display IP address in String
  1043.     OTInetHostToString(ipAddr, buf);
  1044.     printf("HTTP Server on <%s> Starting.\n", buf);
  1045.  
  1046.     fflush(stdout);
  1047.  
  1048.     // Create the listen endpoint.
  1049.     
  1050.     // RRK comments added 8/27/97
  1051.     // In order for the IP address to be re-used after quitting this sample program and
  1052.     // restarting it, the "ReuseAddr" option must be set.
  1053.     // One should be able to set the "ReuseAddr" option as part of the configuration string
  1054.     // however, if you try to do this along with specifying the use of the tilisten
  1055.     // module, the following code hangs the system hard.  As an alternative, the 
  1056.     // endpoint is created with the tilisten module layered above tcp.  After that the
  1057.     // OTOptionManagement call is made to set this option.
  1058.     // RRK Comments end
  1059.     
  1060.     //listener = OTOpenEndpoint(OTCreateConfiguration("tilisten,tcp(ReuseAddr=1)"), 0, nil, &err);
  1061.     listener = OTOpenEndpoint(OTCreateConfiguration("tilisten,tcp"), 0, &Info, &err);
  1062.     
  1063.     // RRK addition 8/27/97
  1064.     // set the ReuseAddr option
  1065.     if (err == noErr) {
  1066.         junk = DoNegotiateIPReuseAddrOption(listener, true);
  1067.         OTAssert("Unable to negotiate raw mode for listener endpoint", junk == noErr);
  1068.     }    
  1069.     // end RRK addition 8/27/97
  1070.  
  1071.     // Set the endpoint mode and bind it to the appropriate IP address.
  1072.     
  1073.     if (err == noErr) {
  1074.         SetDefaultEndpointModes(listener);
  1075.         OTInitInetAddress(&ipAddress, 80, ipAddr);    // port & host ip
  1076.         bindReq.addr.buf = (UInt8 *) &ipAddress;
  1077.         bindReq.addr.len = sizeof(ipAddress);
  1078.         bindReq.qlen = 1;
  1079.         err = OTBind(listener, &bindReq, nil);
  1080.     }
  1081.     
  1082.     while (err == noErr) {
  1083.  
  1084.         // Listen for connection attempts...
  1085.         
  1086.         OTMemzero(&call, sizeof(TCall));
  1087.         call.addr.buf = (UInt8 *) &remoteIPAddress;
  1088.         call.addr.maxlen = sizeof(remoteIPAddress);
  1089.         err = OTListen(listener, &call);
  1090.  
  1091.         // ... then spool a worker thread for this connection.
  1092.         
  1093.         if (err == noErr) {
  1094.         
  1095.             // Create the worker context.
  1096.         
  1097.             workerThread = kNoThreadID;
  1098.             workerContext = OTAllocMem(sizeof(WorkerContext));
  1099.             if (workerContext == nil) {
  1100.                 err = kENOMEMErr;
  1101.             } else {
  1102.                 workerContext->worker = nil;
  1103.                 workerContext->vRefNum = vRefNum;
  1104.                 workerContext->dirID = dirID;
  1105.             }
  1106.             
  1107.             // Open the worker endpoint.
  1108.             
  1109.             if (err == noErr) {
  1110.                 workerContext->worker = OTOpenEndpoint(OTCreateConfiguration("tcp"), 0, nil, &err);
  1111.                 if (err == noErr) {
  1112.                     SetDefaultEndpointModes(workerContext->worker);
  1113.                 }
  1114.             }
  1115.             
  1116.             // Create the worker thread.
  1117.             
  1118.             if (err == noErr) {
  1119.                 err = NewThread(kCooperativeThread,
  1120.                                 (ThreadEntryProcPtr) WorkerThreadProc, workerContext,
  1121.                                 0, kNewSuspend | kCreateIfNeeded,
  1122.                                 nil,
  1123.                                 &workerThread);
  1124.             }
  1125.             
  1126.             // Accept the connection on the thread.
  1127.             
  1128.             if (err == noErr) {
  1129.                 err = OTAccept(listener, workerContext->worker, &call);
  1130.             }
  1131.             
  1132.             // Schedule the thread for execution.
  1133.             
  1134.             if (err == noErr) {
  1135.                 err = SetThreadState(workerThread, kReadyThreadState, kNoThreadID);
  1136.             }
  1137.             
  1138.             // Clean up on error.
  1139.             
  1140.             if (err != noErr) {
  1141.                 if (workerContext != nil) {
  1142.                     if (workerContext->worker != nil) {
  1143.                         junk = OTCloseProvider(workerContext->worker);
  1144.                         OTAssert("StartHTTPServer: Could not close worker", junk == noErr);
  1145.                     }
  1146.                     OTFreeMem(workerContext);
  1147.                 }
  1148.                 if (workerThread != kNoThreadID) {
  1149.                     junk = DisposeThread(workerThread, nil, true);
  1150.                     OTAssert("StartHTTPServer: DisposeThread failed", junk == noErr);
  1151.                 }
  1152.                 printf("StartHTTPServer: Failed to spool worker, error %d.\n", err);
  1153.                 fflush(stdout);
  1154.                 err = noErr;
  1155.             }
  1156.         }
  1157.     }
  1158.     
  1159.     // Clean up the listener endpoint.
  1160.     
  1161.     if (listener != nil) {
  1162.         junk = OTCloseProvider(listener);
  1163.         OTAssert("StartHTTPServer: Could not close listener", junk == noErr);
  1164.     }
  1165.  
  1166.     printf("HTTP Server on %08x: Stopping.\n", ipAddr);
  1167.     fflush(stdout);
  1168.     
  1169.     return (err);
  1170. }
  1171.